<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="!hasLogin || empty===true" class="empty">
			<image src="/static/emptyCart.jpg" mode="aspectFit"></image>
			<view v-if="hasLogin" class="empty-tips">
				空空如也
				<navigator class="navigator" v-if="hasLogin" url="../index/index" open-type="switchTab">随便逛逛></navigator>
			</view>
			<view v-else class="empty-tips">
				空空如也
				<view class="navigator" @click="navToLogin">去登录></view>
			</view>
		</view>
		<view v-else>
			<!-- <view class="header">
				<text>全场最高优惠11元</text>
				<view @click="toggleMask('show')">去领卷<text class="yticon icon-you icon-yticon"></text></view>
			</view> -->

			<!-- 列表 -->
			<ul class="cart-list">
				<li v-for="(item, index) in cartList" :key="item.id" class="list-message" :style="{ left: -(item.left) + 'rpx' }" >
					<view class="cart-item" :class="{'b-b': index!==cartList.length}"  @touchstart="drawStart" @touchmove="drawMove" @touchend="drawEnd" :data-atem="index">
						<view class="checkList">
							<view class="yticon icon-xuanzhong2 checkbox" :class="{checked: item.checked}" @click="check('item', index)"></view>
						</view>
						<view class="image-wrapper">
							<image :src="item.cover_pic"
								:class="[item.loaded]"
								mode="aspectFill" 
								lazy-load 
								@load="onImageLoad('cartList', index)" 
								@error="onImageError('cartList', index)"
								@click="navToDetailPage(item.id)"
							></image>
						</view>
						<view class="item-right">
							<text class="clamp title">{{item.name}}</text>
							<text class="attr">库存：{{item.goods_num}}</text>
							<view class="price-num">
								<text class="price">¥{{item.price}}</text>
								<uni-number-box class="step" :min="1" :max="item.goods_num" :value="item.num>item.goods_num?item.goods_num:item.num"
								 :isMax="item.num>=item.ngoods_num?true:false" :isMin="item.num===1" :index="index"
								 @eventChange="numberChange"></uni-number-box>
							</view>
						</view>
						<view class="del-btn" @click="deleteCartItem(index)">删除</view>
					</view>
				</li>
			</ul>
			<button type="default" @click="clearCar">清空购物车</button>
			<!-- 猜你喜欢 -->
			<view class="guess">
				<view class="guess-title">
					<text class="squareS"></text>
					<text class="squareM"></text>
					<h3>猜你喜欢</h3>
					<text class="squareM"></text>
					<text class="squareS"></text>
				</view>

				<ul class="guess-list">
					<li v-for="(item,index) in guessList" :key="index" data-atem="index" @click="navToDetailPage(item.id)">
						<view>
							<image :src="item.cover_pic"></image>
							<view class="guess-count">
								<text>{{item.name}}</text>
								<text>￥{{item.price}}</text>
							</view>
						</view>
					</li>
				</ul>
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="checkbox">
					<image :src="allChecked?'/static/checkStart.png':'/static/select.png'" mode="aspectFit" @click="check('all')"></image>
					<view class="clear-btn" :class="{show: allChecked}" @click="check('all')">
						全选
					</view>
				</view>
				<view class="total-box">
					<text class="price">¥{{total}}</text>
					<text class="coupon">
						已优惠
						<text>{{preferential}}</text>
						元
						购买将会获得<text>{{total}}</text>积分
					</text>
				</view>
				<button type="primary" class="no-border confirm-btn" @click="createOrder">去结算</button>
			</view>
			<!-- 优惠券面板 -->
			<!-- <view class="mask" :class="maskState===0 ? 'none' : maskState===1 ? 'show' : ''" @click="toggleMask">
				<view class="mask-content" @click.stop.prevent="stopPrevent">
					<view class="receive">
						<text>领取微信优惠券</text>
						<text class="receive-cha" @click="discountDetail">×</text>
					</view>
					<view class="coupon-count">
						<view class="coupon-item" v-for="(item,index) in couponList" :key="index">
							<view class="con">
								<view class="left">
									<text class="title">{{item.title}}</text>
									<text class="times">满199减110</text>
									<text class="time">2020-04-27-2020.05.31</text>
								</view>
								<view class="dashed"></view>
								<view class="right" :data-count="index" @click="imReceive">{{item.content}}</view>
								<view class="circle l"></view>
								<view class="circle r"></view>
							</view>
							<text class="tips">微信支付</text>
						</view>
					</view>
				</view>
			</view> -->
		</view>

	</view>
</template>

<script>
	import url from '../../components/hosturl.js'
	import Vue from 'vue';
	import {
		mapState
	} from 'vuex';
	import uniNumberBox from '@/components/uni-number-box.vue';
	export default {
		components: {
			uniNumberBox
		},
		data() {
			return {
				maskState: 0, //优惠券面板显示状态
				showcoupon: false, //优惠券
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				//猜你喜欢
				guessList: [],
				hasLogin: false,
				result:[],
				cartList:[],
				carListArr: [],
				preferential: 0, //优惠
				bol: false,
				startX: 0,
				delBtnWidth: 120,
				couponList: [{title: '50',price: 5,content: '立即领取'},
					{title: '110',price: 10,content: '立即领取'},
					{title: '20',price: 15,content: '立即领取'},
					{title: '200',price: 20,content: '立即领取'}
				],
			};
		},

		onLoad() {
			var obj={image:this.$store.state.image,attr_val:this.$store.state.title,checked:true,id:3,loaded:'loaded',number:this.$store.state.number,stock:15,title:this.$store.state.title,price:this.$store.state.price};
			// this.cartList.push(obj);
			
			
		},
		onShow() {
			uni.request({
				method:'get',
				url:url+'/Shopping/getShoppingCar',
				data:{
					'token':uni.getStorageSync('token')
				},
				success:(res)=>{
					this.cartList = res.data.message;
					this.empty = this.cartList.length == 0;
					if(this.cartList>0){
						for(let i=0;i<this.cartList.length;i++){
							this.cartList[i].left = 0;
							this.cartList[i].checked = true;
						}
					}
				}
			})
			this.loadData();
			// 猜你喜欢
			uni.request({
				method:'get',
				url:url+'/Shopping/getShoppRecommend',
				success:(res)=>{
					this.guessList = res.data.message;
				}
			})
		},
		mounted() {
			this.cartLists(),
			this.hasLogin = uni.getStorageSync('login')
		},
		watch: {
			
		},
		computed: {
			...mapState(['hasLogin'])
		},
		methods: {
			//显示空白页
			cartLists() {
				this.empty = this.cartList.length > 0 ? false : true;
			},
			//猜你喜欢
			navToDetailPage(id) {
				uni.navigateTo({
					url: `/pages/classify/product?id=`+id
				})
			},
			clearCar(){
				uni.request({
					url:url+'/Shopping/deleteAllCar',
					data:{
						'token':uni.getStorageSync('token'),
					},
					succes:res=>{
						console.log(res)
					}
				})
				this.cartList = this.cartList.splice(0,this.cartList.length)
				this.cartLists();
			},
			//领取优惠券
			imReceive(e) {
				if (this.couponList[e.currentTarget.dataset.count].content == '立即领取') {
					this.couponList[e.currentTarget.dataset.count].content = '已领取';
					wx.showToast({
						title: '领取成功',
					});
				} else {
					wx.showToast({
						title: '已领取',
					});
				}
			},
			//关闭优惠券面板
			discountDetail(){
				this.maskState = 0;
			},
			stopPrevent(){},
			//显示优惠券面板
			toggleMask(type) {
				let timer = type === 'show' ? 10 : 300;
				let state = type === 'show' ? 1 : 0;
				this.maskState = 2;
				setTimeout(() => {
					this.maskState = state;
				}, timer);
			},
			//滑动删除
			drawStart: function(e) {
				if(e.touches.length==1){
					this.startX = e.touches[0].clientX;
				}
			},
			drawMove: function(e) {
				if(e.touches.length==1){
					let moveX = e.touches[0].clientX;
					let disX = this.startX - moveX;
					let txtStyle = 0;
					if (disX == 0 || disX < 0) {
                        txtStyle = 0;
                    } else if(disX > 0){
                        txtStyle = disX;
                        if (disX >= this.delBtnWidth) {
                           
                            txtStyle = this.delBtnWidth;
                        }
                    }
                    //获取手指触摸的是哪一项
                    var index = e.currentTarget.dataset.atem;
					this.$set(this.cartList[e.currentTarget.dataset.atem],'left',txtStyle)
				}	
			},
			drawEnd: function(e) {
				if(e.changedTouches.length==1){
					var endX = e.changedTouches[0].clientX;
					var disX = this.startX - endX;
					let delBtnWidth = this.delBtnWidth;
					let txtStyle = disX >= delBtnWidth/2?delBtnWidth:0;
					this.$set(this.cartList[e.currentTarget.dataset.atem],'left',txtStyle)
				}
			},
			//请求数据
			async loadData() {
				// let list = await this.$api.json('cartList');
				// let cartList = list.map(item => {
				// 	item.checked = true;
				// 	return item;
				// });
				// this.cartList = cartList;
				this.calcTotal(); //计算总价
			},

			//监听image加载完成
			onImageLoad(key, index) {
				this.$set(this[key][index], 'loaded', 'loaded');
			},
			//监听image加载失败
			onImageError(key, index) {
				this[key][index].image = '/static/errorImage.jpg';
			},
			navToLogin() {
				uni.navigateTo({
					url: '/pages/public/login'
				})
			},
			//选中状态处理
			check(type, index) {
				if (type === 'item') {
					this.cartList[index].checked = !this.cartList[index].checked;
				} else {
					const checked = !this.allChecked
					const list = this.cartList;
					list.forEach(item => {
						item.checked = checked;
					})
					this.allChecked = checked;
				}
				this.calcTotal();
			},
			//数量
			numberChange(data) {
				this.cartList[data.index].num = data.number;
				this.calcTotal();
			},
			//删除
			deleteCartItem(index) {
				let list = this.cartList;
				let row = list[index];
				console.log(row);
				let id = row.id;
				console.log(id);
				uni.request({
					method:'post',
					url:url+'/Shopping/deleteShoppingCar',
					header: {
					    "Content-Type": "application/x-www-form-urlencoded"
					},
					data:{
						'token':uni.getStorageSync('token'),
						'sid': id
					},
					success:(res)=>{
						this.cartList.splice(index, 1);
						this.calcTotal();
						uni.hideLoading();
					}
				})
			},
			
			//计算总价
			calcTotal() {
				let list = this.cartList;
				if (list.length === 0) {
					this.empty = true;
					return;
				}
				this.total = 0;
				for(let i=0;i<list.length;i++){
					if(list[i].checked){
						console.log('price1: '+list[i].price+'  num1: '+list[i].num);
						this.total += Number(list[i].price) * Number(list[i].num);
					}
				}
				
			},
			//创建订单
			createOrder() {
				let list = this.cartList;
				// let price = this.total;
				let price = {
					"price":this.total
				}
				let goodsData = [];
				list.forEach(item => {
					if (item.checked) {
						goodsData.push({
							attr_val: item.attr_val,
							number: item.num
						})
					}
				})

				uni.navigateTo({
					url:'/pages/shoppingcart/createOrder?index='+encodeURIComponent(JSON.stringify(goodsData))
					// url: `/pages/shoppingcart/createOrder?data=${JSON.stringify({
					// 	goodsData: goodsData,
					// 	price:this.total
					// })}`
				})
				console.log(goodsData);
				// this.$api.msg('跳转下一页 sendData');
			}
		}
	}
</script>

<style lang='scss'>
	/* 猜你喜欢 */
	.guess-title { align-items: center; display: flex; justify-content: center; }
	.guess-title .squareS { background: #dedede; display: block; height: 12rpx; width: 12rpx; transform: rotate(45deg); }
	.guess-title .squareM { background: #dedede; height: 18rpx; width: 18rpx; transform: rotate(45deg); margin: 0 20rpx; }
	.guess-title h3 { color: #040404; font-size: 30rpx; text-align: center; line-height: 90rpx; }
	.guess-list { display: flex; flex-wrap: wrap; justify-content: space-between; margin: 0 auto; width: 93.3%; }
	.guess-list li { height: 545rpx; width: 49.1%; background: #fff; border-radius: 8rpx; margin-bottom: 16rpx; }
	.guess-count { height: 135rpx;display: flex;flex-direction: column;font-weight: bold;justify-content: space-around;margin: 0 auto;width: 86.6%;}
	.guess-count text:nth-of-type(1) { color: #2b2b2b;font-size: 26rpx;}
	.guess-count text:nth-of-type(2) { color: #ff3e4d;font-size: 28rpx;}
	.guess-list image { border-top-left-radius: 8rpx;border-top-right-radius: 8rpx;height: 410rpx; margin: 0 auto; width: 100%; }
	.coupon-s { background: rgba(0, 0, 0, 0.5);	height: 100%;position: absolute;left: 0;top: 0;width: 100%;z-index: 100; }
	.coupon-footer { background: #fff;left: 0;position: absolute;top: 0; }
	/* 优惠券面板 */
	.mask {background: rgba(0, 0, 0, 0);bottom: 0;display: flex;align-items: flex-end;left: 0;position: fixed;transition: .3s;top: var(--window-top);width: 100%;z-index: 9995;
		&.none { display: none; }
		&.show { background: rgba(0, 0, 0, .4);
			.mask-content { transform: translateY(0);} } }
	.mask .mask-content { background: #f3f3f3; border-top-right-radius: 20rpx; border-top-left-radius: 20rpx; left: 0; top: 0;  position: relative; transform: translateY(100%); transition: .3s; height: 60vh; width: 100%;}
	.receive { background: #fff; border-top-right-radius: 20rpx; border-top-left-radius: 20rpx; color: #0b0b0b; font-size: 32rpx; height: 106rpx; line-height: 106rpx; left: 0; position: absolute; text-align: center; top: 0; width: 100%; z-index: 200; }
	.receive-cha { font-size: 36rpx; position: absolute; right: 30rpx; top: 0; }
	/* 优惠券列表 */
	.coupon-count { margin-top: 106rpx; padding-bottom: 100rpx; height: 100%; overflow-y: scroll; }
	.coupon-item {  background: #fff; color: #fff; display: flex; flex-direction: column; margin: 20upx 24upx;
		.con { align-items: center; background: #a387eb; display: flex; height: 160rpx; padding: 0 30upx; position: relative;
			&:after { bottom: 0; content: ''; border-bottom: 1px dashed #f3f3f3; height: 0; left: 0; position: absolute; transform: scaleY(50%); width: 100%; } }
		.left { display: flex; flex-direction: column; height: 100upx; flex: 1; justify-content: center; overflow: hidden; }
		.title { font-size: 32rpx; margin-bottom: 10upx;
			&:before { content: '￥'; font-size: 22rpx; } }
		.time { font-size: 18rpx; }
		.times { font-size: 24rpx; }
		.right { font-size: 28rpx; text-align: center; padding-left: 30rpx; }
		.dashed { border-left: 1px #fff dashed; height: 100%; }
		.tips { color: $font-color-light; font-size: 24upx; line-height: 60upx; padding-left: 60upx;background: url(../../static/wx.png) no-repeat;background-size: 24rpx 24rpx;background-position: 30rpx center; }
		.circle { bottom: -10upx; background: #f3f3f3; border-radius: 100px; height: 20upx; left: -6upx; position: absolute; width: 20upx; z-index: 10;
			&.r { left: auto; right: -6upx;} } }
	.container {background: #f7f7f7;padding-bottom: 134upx;position: relative;}
	.container .empty { align-items: center; background: #fff; display: flex; flex-direction: column; height: 100vh; justify-content: center;left: 0;padding-bottom: 100upx;position: fixed;top: 0;width: 100%;}
	.container .empty image { height: 160upx; margin-bottom: 30upx; width: 240upx;}
	.container .empty .empty-tips { color: $font-color-disabled; display: flex; font-size: $font-sm+2upx; }
	.container .empty .empty-tips .navigator { color: $uni-color-primary; margin-left: 16upx; }

	.header { align-items: center; background-color: #fff; display: flex; font-size: 28rpx; height: 110rpx; justify-content: space-between; padding: 0 4.2%; }
	.header text { color: #2d2f2c; }
	.header view { color: #2d2f9c; text-align: right; width: 50%; }
	.header view text { color: #2d2f9c; }
	.icon-yticon {margin-left: 10rpx;}
	/* 购物车列表项 */
	.cart-list { align-items: center;display: flex;flex-direction: column;overflow: hidden; }
	.list-message { background-color: #fff; border-radius: 25rpx; height: 285rpx; position: relative; margin-top: 25rpx; left: 0; top: 0;width: 93.85%; }
	.cart-item { align-items: center; display: flex; height: 100%; padding: 30rpx 30rpx 30rpx 0; position: relative; left: 0; top: 0; }
	.cart-item .image-wrapper { height: 185rpx; width: 185rpx; }
	.cart-item .image-wrapper image { border-radius: 8upx; }
	.cart-item .checkbox { background: #fff; border-radius: 50px; color: $font-color-disabled; font-size: 44upx; padding: 4upx; }
	.cart-item .checkList { align-items: center; display: flex; padding: 0 24rpx; }
	.cart-item .item-right { display: flex; flex-direction: column; height: 185rpx; justify-content: space-between; overflow: hidden; padding-left: 30upx; width: 60%; }
	.cart-item .item-right .title,.cart-item .item-right .price{ color: $font-color-dark; font-size: $font-base + 2upx; height: 40upx; line-height: 40upx; }
	.cart-item .item-right .attr { color: $font-color-light; font-size: $font-sm + 2upx; height: 50upx; line-height: 50upx; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;}
	.cart-item .item-right .price { height: 50upx; line-height: 50upx; }
	.cart-item .del-btn { align-items: center; background: #f60; color: #fff; display: flex; font-size: 34upx; height: 285rpx; justify-content: center;  position: absolute; right: -125rpx; top: 0; transition: .5s; width: 100rpx; }
	.price-num { height: 55rpx; position: relative; width: 100%; }
	.step { bottom: -10rpx; height: 50rpx; left: 30%; position: absolute; width: 40%; }

	/* 底部栏 */
	.action-section { align-items: center; background: #fff; bottom: 0; display: flex; height: 110upx; left: 0; position: fixed; padding: 0 30upx; width: 100%; z-index: 95; }
	.action-section .checkbox { height: 52upx; position: relative; }
	.action-section .checkbox image { height: 100%; position: relative; width: 52upx; z-index: 5;  }
	.action-section .clear-btn { border-radius: 0 50px 50px 0; background: #a387eb; color: #fff; font-size: $font-base; height: 52upx; left: 26upx; line-height: 52upx; opacity: 0; padding-left: 38upx; position: absolute; transition: .2s; top: 0; width: 0; z-index: 4;
	&.show { opacity: 1; width: 120upx; } }
	.action-section .total-box { display: flex; flex: 1; flex-direction: column; text-align: right; padding-right: 40upx; }
	.action-section .total-box .price { color: $font-color-dark; font-size: $font-lg; }
	.action-section .total-box .coupon { color: $font-color-light; font-size: $font-sm; }
	.action-section .total-box .coupon text { color: $font-color-dark; }
	.action-section .confirm-btn { background: #a387eb; box-shadow: 1px 2px 5px rgba(163, 135, 235, 0.72); border-radius: 100px; height: 76upx; font-size: $font-base + 2upx; line-height: 76upx; padding: 0 38upx; margin: 0; }
	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked { color: #a387eb; }
</style>
